import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { getToken } from '@/utils/token'
// import responseCode from '@/utils/responseCode'
import { tansParams, blobValidate } from '@/utils/common'
import cache from '@/plugins/cache'
import { saveAs } from 'file-saver'
import useUserStore from '@/store/modules/user'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.headers['Accept-Language'] = 'zh_CN'

const api = axios.create({
  baseURL: (import.meta.env.DEV && import.meta.env.VITE_OPEN_PROXY) ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
  timeout: 10000
})

api.interceptors.request.use(
  (request) => {
    // 全局拦截请求发送前提交的参数
    const userStore = useUserStore()
    
    // 是否需要设置 token
    const isToken = ((request.headers || {}) as any).isToken === false
    if (request.headers) {
      if (userStore.isLogin && !isToken) {
        request.headers['Authorization'] = 'Bearer ' + getToken() 
      }
    }
    // get请求映射params参数
    if (request.method === 'get' && request.params) {
      let url = request.url + '?' + tansParams(request.params);
      url = url.slice(0, -1);
      request.params = {};
      request.url = url;
    }
    // 是否需要防止数据重复提交
    const isRepeatSubmit = ((request.headers || {}) as any).repeatSubmit === false
    if (!isRepeatSubmit && (request.method === 'post' || request.method === 'put')) {
      const requestObj = {
        url: request.url,
        data: typeof request.data === 'object' ? JSON.stringify(request.data) : request.data,
        time: new Date().getTime()
      }
      const sessionObj = cache.session.getJSON('sessionObj')
      if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
        cache.session.setJSON('sessionObj', requestObj)
      } else {
        const s_url = sessionObj.url;                // 请求地址
        const s_data = sessionObj.data;              // 请求数据
        const s_time = sessionObj.time;              // 请求时间
        const interval = 1000;                       // 间隔时间(ms)，小于此时间视为重复提交
        if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
          const message = '数据正在处理，请勿重复提交';
          console.warn(`[${s_url}]: ` + message)
          return Promise.reject(new Error(message))
        } else {
          cache.session.setJSON('sessionObj', requestObj)
        }
      }
    }
    return request
  }, error => {
    console.log(error)
    Promise.reject(error)
  })

api.interceptors.response.use(
  (response) => {
    if (response.request.responseType === "blob" || response.request.responseType === "arraybuffer") {
      return response.data;
    }
    const code = response.data.code || 200;
    const msg = response.data.msg ;
    if (code === 401) {
      useUserStore().requestLogout()
      return Promise.reject("\u65E0\u6548\u7684\u4F1A\u8BDD\uFF0C\u6216\u8005\u4F1A\u8BDD\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002");
    } else if (code === 500) {
      ElMessage.error(msg)
      return Promise.reject(msg);
    } else if (code === 601) {
      ElMessage.error(msg)
      return Promise.reject(msg);
    } else if (code !== 200) {
      return Promise.reject("error");
    }
    // else {
    //   useUserStore().requestLogout()
    // }
    return Promise.resolve(response.data)
  },
  (error) => {
    if (error.status === 401) {
      useUserStore().requestLogout()
      throw error
    }
    let message = error.message
    if (message === 'Network Error') {
      message = '后端网络故障'
    }
    else if (message.includes('timeout')) {
      message = '接口请求超时'
    }
    else if (message.includes('Request failed with status code')) {
      message = `接口${message.substr(message.length - 3)}异常`
    }
    ElMessage.error(message)
    return Promise.reject(error)
  },
)

export default api

let downloadLoadingInstance:any;

// 通用下载方法
export function download(url:string, params:any, filename:string, config:any) {
  downloadLoadingInstance = ElLoading.service({ text: "正在下载...", background: "rgba(0, 0, 0, 0.7)", })
  return api.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data:any) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg =rspObj.msg;// responseCode[rspObj.code] || rspObj.msg || responseCode['default']
      ElMessage.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    ElMessage.error('下载文件失败！')
    downloadLoadingInstance.close();
  })
}